import request from '@/utils/request'
import { defineStore } from 'pinia'
import { ApiRes, CategoryItem, TopCategoryItem, SubCategory } from '@/types/data'
import { topCategory  } from '../constants'
const defaultCategory = topCategory.map(item => {
  return {
    name: item
  }
})


export default defineStore('category', {
  state() {
    return {
      money: 100,
      // 分类的列表数据
      list: defaultCategory as CategoryItem[],
      // 一级分类
      topCategory: {} as TopCategoryItem,
      // 二级分类
      subCategory: {} as SubCategory
    }
  },
  actions: {
    async getAllCategory() {
      const res = await request.get<ApiRes<CategoryItem[]>>('/home/category/head')
      // 遍历数据, 给每一个一级分类添加属性open , 用来控制当前分类的显示和隐藏
      res.data.result.forEach(item => item.open = false)
      // console.log('--分类的列表数据--', res.data.result);
      this.list = res.data.result
    },
    // 二级分类弹层的显示
    show(id: string) {
      // category指的是当前的鼠标移入分类对应的数据
      const category = this.list.find(item => item.id === id )
      // 非空断言
      category!.open = true
    },
    // 二级分类弹层的隐藏
    hide(id: string) {
      const category = this.list.find(item => item.id === id )
      category!.open = false
    },
    // 获取一级/顶级分类数据
    async getTopCategory(id: string) {
      // const res = await request.get(`/category?id=${id}`)
      const res = await request.get<ApiRes<TopCategoryItem>>(`/category`, {
        params: {
          id
        }
      })
      console.log('--顶级分类的数据--', res.data);
      this.topCategory = res.data.result
    },
    // 获取二级分类的数据
    async getSubFilter(id: string) {
      const res = await request.get<ApiRes<SubCategory>>('/category/sub/filter', {
        params: {
          id
        }
      })
      console.log('--二级分类的数据--', res);
      this.subCategory = res.data.result
    }
  }
})